module Main where
import Libp2p.Mux.Config
import qualified Libp2p.Mux.Types as MT
import Libp2p.Mux.Internal
import Data.Default
import Network.Socket
import Control.Monad.Trans.Except
import qualified Control.Concurrent.Actor as Act
import qualified Data.ByteString as BS
import qualified Control.Concurrent.STM.TMVar as TMVar
import qualified Control.Monad.STM as STM
import System.Log.FastLogger
import qualified Control.Monad as M
import Control.Monad.Trans.Class

main :: IO ()
main = do
  withSocketsDo $ do
   addr <- resolve "3000"
   sock <- open addr
   sess <- mkSession sock (def {keepAliveInterval = 3000}) True
   runExceptT $ do  
      accStream <- acceptStream sess
      buf <- streamRead accStream 4
      lift $ print buf
   Act.sleep 5000000
   closeSession sess
   --either (print) (\s-> do
   --                    putStrLn "New Stream Success"
   --                    M.forM_ (replicate 600 1) (\n -> streamWrite s $ BS.pack $ replicate 1024 6)
   --               ) stream
   --Act.sleep 8000000
   --STM.atomically $ TMVar.putTMVar (MT.shutdownCh sess) ()
   Act.wait

testReadData::MT.Session -> IO ()
testReadData sess = do
   e <- runExceptT $ do
      stream  <- openStream sess
      buf <- streamRead stream 8
      lift $ print buf
      buf <- streamRead stream 8
      lift $ print buf
      buf <- streamRead stream 8
      lift $ print buf
   print e


resolve::ServiceName -> IO AddrInfo
resolve port = do
   let hints = defaultHints { addrFlags = [AI_PASSIVE] , addrSocketType = Stream }
   addr:_ <- getAddrInfo (Just hints) Nothing (Just port)
   return addr

open::AddrInfo -> IO Socket
open addr = do
   sock <- socket (addrFamily addr) (addrSocketType addr) (addrProtocol addr)
   connect sock $ addrAddress addr
   return sock